// 定义请求路径
const baseUrl = "http://localhost:8080";

/**
 * 返回请求跟路径baseURL
 */
const getBaseURL = ()=>{
  return baseUrl;
}

/**
* 后端请求工具类
*/
const requestUtil=(params)=>{
  return new Promise((resolve,reject)=>{
    wx.request({
      ...params,
      url: baseUrl + params.url,
      success:(result)=>{
        resolve(result.data)
      },
      fail:(err)=>{
        reject(err)
      }
    })
  });
}

/**
 * wx login封装
 */
const getWxLogin = ()=>{
  return new Promise((resolve, reject)=>{
    wx.login({
      timeout: 5000,
      success: (res) => {
        resolve(res)
      },
      fail:(err)=>{
        reject(err)
      }
    })
  });
}
/**
 * wx getUserProfile封装
 */
const getUserProfile = ()=>{
  return new Promise((resolve, reject)=>{
    wx.getUserProfile({
      desc: '获取用户信息',
      success: (res) => {
        resolve(res)
      },
      fail:(err)=>{
        reject(err)
      }
    })
  });
}

/**
 * 学生验证verifyStudent封装
 * @param {*} studentData 
 * @param {*} encryptedopenId 
 */
const verifyStudent = (studentData, encryptedopenId) => {
  return requestUtil({
    url: `/student/verify?encryptedopenId=${encryptedopenId}`,
    data: studentData,
    method: "POST",
    header: {
      "content-type": "application/json" // 指定 JSON 格式
    }
  });
}
/**
 * 发布商品
 * @param {*} params 
 */
const postProduct = (params) => {
  return new Promise((resolve, reject) => {
    wx.request({
      ...params,
      url: baseUrl + params.url,
      success: (result) => {
        resolve(result.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

const getAllProducts = () =>{
  return requestUtil({
    url: "/product/all",
    method: "GET"
  });
}

const chooseMedia = (
  count = 9, 
  mediaType = ['image', 'video'], 
  sourceType = ['album', 'camera']
) => {
  return new Promise((resolve, reject) => {
    wx.chooseMedia({
      count,  // 最多选择的文件数
      mediaType,  // 支持的媒体类型
      sourceType,  // 来源类型（相册、相机）
      success: (res) => {
        resolve(res.tempFiles);  // 返回选择的文件
      },
      fail: (error) => {
        reject(error);  // 选择失败的回调
      },
    });
  });
};

const uploadFile = (filePath, type) => {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: 'http://localhost:9090/upload/media',  // 上传接口
      filePath: filePath,
      name: 'file',  // 上传文件的字段名称
      success: (uploadRes) => {
        const data = JSON.parse(uploadRes.data);
        if (data.code === 200) {
          if (type === 'image') {
            resolve({ code: 200, data: { imageUrl: data.imageUrl } });
          } else if (type === 'video') {
            resolve({ code: 200, data: { videoUrl: data.videoUrl } });
          }
        } else {
          reject(data.message);
        }
      },
      fail: (error) => {
        reject(error);
      },
    });
  });
};


module.exports = {
  getWxLogin,
  getUserProfile,
  requestUtil,
  verifyStudent,
  postProduct,
  getAllProducts,
  chooseMedia,
  uploadFile
}